//index.js
var t = getApp(),
  a = t.requirejs("core"),
  c = t.requirejs("api/index"),
  e = (t.requirejs("icons"), t.requirejs("wxParse/wxParse")); //对图片进行处理
const myAudio = wx.createInnerAudioContext();
Page({
  data: {
		statusBar: t.globalData.statusBar,
		customBar: t.globalData.customBar,
		custom: t.globalData.custom,
    store: '入驻',
    company_status: '',
    route: "power",
    menu: t.tabBar,
    menu_show: false,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    circular: true,
    icons: t.requirejs("icons"),
    total: 0,
    page: 1,
    show: false,
    display: false,
    card_id: 0,
    show_chat: 0,
    get_phone: true,
    hotimg: "/yb_mingpian/static/images/hotdot.jpg",
    notification: "/yb_mingpian/static/images/notification.png",
    default_pic: '/yb_mingpian/static/images/add_pic.jpg',
    background: t.config.background,
    showtabbar: false,
    markers: [{
      iconPath: "/yb_mingpian/static/images/red_position_icon.png",
      title: '地理位置',
      latitude: 34.6284500000,
      longitude: 112.4282100000,
      width: 50,
      height: 50,
      callout: {
        content: '公司位置',
        company: '',
        color: '#000',
        fontSize: 14,
        borderRadius: 5,
        display: 'ALWAYS',
        textAlign: 'center',
        padding: 10,
        // borderWidth:1,
        // borderColor:"#ddd",
        bgColor:'#fff'
      }
    }],
    video: false,
    config: t.config,
    id: "0",
    bookData: {}, //清空表单数据用
    bus: {
      'name': '公司名称',
      logo: '/yb_mingpian/static/card/pt-img15.png',
    },
    background: '/yb_mingpian/static/card/pt-img67.png',
    page_type: 3,
    shop_site: " ",
    isPlay: false,
    nowtime: "00:00",
    totalTime: '',
    currecttime: 0,
    timechanging: false,
    audioIndex: -1,
    page_info: {},
    openImg: false,
    disabled:'',
    titlelist:[
      {
        cate_name:"推荐",
        cate_id:1,
      },  
    ],
    titleActive:1,
    type:1,
    datalist:[]
  },
  checkTitle:function(e){ 
    this.setData({
      titleActive: e.currentTarget.dataset.cate_id,
      type: e.currentTarget.dataset.type,
    })
    let that = this
    if (e.currentTarget.dataset.cate_id != 1){
      wx.showLoading({ title: '加载中...' });
      if (e.currentTarget.dataset.type == 2){
        a.get('store/list', {
          page: 1,
          cate_id: e.currentTarget.dataset.cate_id
        }, function (t) {
          wx.hideLoading();
          console.log("店铺列表",t)
          that.setData({
            datalist: t.info
          })

        })
      }else{
        a.get('goods/GoodsList', {
          page:1,
          cate_id: e.currentTarget.dataset.cate_id
        }, function (t) { 
          wx.hideLoading();
          that.setData({
            datalist:t.info
          })

        })
      }
    }
  
   
  },
  //底部导航跳转
  menu_url: function(k) {
    a.menu_url(k, 2);
  },
	// 点击充值弹窗
	 submit: function () {
		 this.setData({
		 showModal: true
		 })
	 },
	 close_mask: function () {
		 this.setData({
		 showModal: false
		 })
	 },
  onPageScroll: function(e) { // 获取滚动条当前位置
    // var that = this;
    // var music = that.data.music;
    // if (music && music.url) {
    //   c.play_music(music.name ? music.name : 'Arliki', music.author ? music.author : 'Arliki', music.imgurl, music.url)
    // }
  },
  //跳转+收集表单id
  formSubmit: function(k) {
    var e = {},
      vv = {
        currentTarget: {
          dataset: {}
        }
      },
      data = k.detail.value;
    vv.currentTarget.dataset = data; 
    a.menu_url(vv, 1);
    console.log("vv",vv);
    e.formid = k.detail.formId;
    e.openid = getApp().getCache("userinfo").openid;
    e.username = getApp().getCache("userinfo").nickName;
    console.log('======',e)
    a.get('Market/getFormid', e, function(t) {
      console.log(t)
    })
  },
  //跳转
  to_url: function(k) {
    console.log(k);
    a.menu_url(k, 1);
  },
  // //跳转
  // to_url: function (k) {
  //   var data = a.pdata(k),
  //     url = data.url ? data.url : '',
  //     appid = data.appid ? data.appid : '',
  //     path = data.path ? data.path : '',
  //     title = data.title ? data.title : '',
  //     path = data.path ? data.path : '',
  //     title = data.title ? data.title : '';
  //   c.to_url(data.key, url, appid, path, title);
  // },
  onGotUserInfo: function(q) {
    var that = this,
        e = t.getCache("userinfo");

    if (e) {
      // that.setData({
      //   display: false
      // })
      //return;
    }
    t.getUserInfo(q.detail.userInfo, function(v) {
      if (v != 1000) {
        var ucache = getApp().getCache("userinfo");
        if (ucache) {
          t.userlog(1, '商城', 'shop_browse');
          t.get_news_num(that);
          that.setData({
            display: false,
            getPhoneAuth: getApp().globalData.getphone
          })
        }
        // that.getList();
        // that.setData({
        //   display: false
        // })
      } else {
        that.setData({
          display: true
        })
      }

    }, q.detail.encryptedData, q.detail.iv);

  },
  Switch: function() {
    var o = this
  a.get("Card/Switch",{
    // user_id: t.getCache("userinfo").uid,
  }, function (res) {
    console.log(res)
    o.setData({
      disabled: res.disabled 
   })
 })
  },
  // 授权获取用户信息判断
  authCheck: function () {
    var cache = getApp().getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      this.setData({
        display: true
      })
      return false;
    } else {
      this.setData({
        display: false
      })
      return true;
    }
  },

  // 取消登录
  cancel_auth: function () {
    this.setData({
      display: false
    })
  },

  onLoad: function(options) {
    this.Switch();
    this.jiazai();
    var that = this;
    // var hidet = t.getCache('hideTabBar');
    // if (!hidet) {
    //   wx.hideTabBar();
    //  t.setCache('hideTabBar', 111);
    // } 
    a.get('goods/GetCate', { 
    }, function (t) {
    
      let titlelist = that.data.titlelist.concat(t.info)
      console.log('商品数据但是公司的', titlelist)
      that.setData({
        titlelist
      })
    })



    var che = t.getCache("userinfo");
    console.log("che",che);
   
   
    if (!che.nickName && !che.avatarUrl) {
      getApp().authSwitch(function(res){
        if (res == 1) {
          that.setData({
            display: true
          })
        } else {
          if (che) {
            that.setData({
              display: false
            })
          } else {
            that.setData({
              display: true
            })
          }
        }
      })
    }

    if (options && options.card_id) {
      t.globalData.card_id = options.card_id;
    }
    // t.set_caidan(function() {
    //   a.setting();
    //   that.setData({
    //     config: getApp().config
    //   })
    // });
		wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: getApp().config.nv_color,
		})
    if (options && options.pid) {
      t.set_share_pid(options.pid);
      t.setCache('pid', options.pid);
    }
    if (options && options.scene) {
      t.set_share_pid(options.scene);
      t.setCache('pid', parseInt(options.scene));
    }
    // t.set_caidan();
    that.getList();
  },
  to_zhaopin: function(e) {
    var that = this,
      id = a.pdata(e).id;
    if (id) {
      a.jump('/yb_mingpian/pages/zhaopin/index?id=' + id);
    }
  },
  formBook: function(e) {
    var auth_res = this.authCheck();
    if (!auth_res) {
      return;
    }

    var that = this,
      data = e.detail.value,
      uid = getApp().getCache("userinfo").uid;
    if (data.name == '') {
      a.error('姓名不能为空');
      return;
    } else if (uid == null) {
      a.error('请先登录');
      setTimeout(function() {
        a.jump('/yb_mingpian/pages/index/index', 2);
      }, 1000)
      return;
    } else if (data.phone.length != 11) {
      a.error('手机号格式不正确');
      return;
    }
    // else if (data.booktime == '') {
    //   a.error('预约时间不能为空');
    //   return;
    // }

    data.user_id = uid;
    a.get('Index/WriteBook', data, function(t) {
      if (t.code == 0) {
        that.setData({
          bookData: {}
        });
        a.success('提交成功');
      } else {
        a.alert(t.msg);
      }
    })

  },
  onHide: function() {
    myAudio.destroy();
    if (this.data.page_type == 3) {
      t.setCache('back_menu', 'shop', 2);
    }
  },
  onShow: function() {
    this.jiazai();
    console.log(21);
    var that = this;

    t.set_caidan();
    t.get_news_num(that);
    that.setData({
      card_id: t.globalData.card_id
    })
    var che = t.getCache("userinfo");
    if (che) {
      t.userlog(1, '商城', 'shop_browse');
    }
    var back_menu = t.getCache('back_menu');

    if (that.data.page_type != 3 && back_menu) {
      that.getList();
    }
  },
  getList: function() {
    var that = this,
      id = that.data.id;
    var uid = getApp().getCache("userinfo").uid != undefined ? getApp().getCache("userinfo").uid : 0;
    a.get('shop/info', {
      uid: uid,
    }, function(t) {
      console.log('商品数据',t)
      if (t.code == 0) {
        that.setData({
          num: t.info
        })
      }

    })

    c.indexMod(that, function(t) {
      that.setData(t);
      wx.setNavigationBarTitle({
        title: t.shop_page_name ? t.shop_page_name : "商城"
      })

      that.setData({
        page_info: t.page
      });

      // 开屏弹窗广告
      var showopenimg = getApp().getCache('shop_open_img_show');
      var open_img_url = that.data.page_info.open_img.imgurl;
      if ((open_img_url != undefined && open_img_url != '') && (showopenimg == undefined || showopenimg == '')) {
        that.setData({
          openImg: true
        });
      } else {
        that.setData({
          openImg: false
        });
      }
    }, 'ModShop')
  },

  // 关闭开屏弹窗广告
  openImg_close:function(){
    this.setData({
      openImg: false
    });
    // 半天弹1次
    t.setCache('shop_open_img_show', true, 3600*12);
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    let that = this
    if (that.data.titleActive != 1) {
      wx.showLoading({ title: '加载中...' });
      if (that.data.type == 1){
        a.get('goods/GoodsList', {
          page: 1,
          cate_id: that.data.titleActive
        }, function (t) {
          wx.hideLoading();
          that.setData({
            datalist: t.info
          })
        })
      } else if (that.data.type == 2){
       
        a.get('store/list', {
          page: 1,
          cate_id: that.data.titleActive
        }, function (t) {
          wx.hideLoading();
          that.setData({
            datalist: t.info
          })
        })
      }
    }else{
      this.onLoad() ||this.onShow()
    }
    wx.stopPullDownRefresh();
  },
  
 
  /**
   * 地图
   */
  navigate: function(e) {
    var t = a.pdata(e);
    if (t.name && t.lat && t.lng) {
      a.tx_map(t.lat, t.lng, t.name, this.data.markers[0].callout.company)
    } else {
      a.toast('不能获取到该位置')
    }
  },

  phone: function(t) {
    a.phone(t)
  },
  // 万能表单提交
  formPower: function(e) {
    c.formSubmit(this, e);
  },
  bindPickerChange: function(e) {
    c.bindPickerChange(this, e);
  },
  listen_time_two: function(e) {
    c.listen_time_two(this, e);
  },
  chooseImageTap1: function(e) {
    var id = a.pdata(e).id;
    c.upload(this, id, 'form_pic', 1)
  },
  chooseImageTap2: function(e) {
    var id = a.pdata(e).id;
    c.upload(this, id, 'form_pic', 0)
  },
  Image_del: function(e) {
    c.Image_del(this, e);
  },
  /**
   * 图片预览
   */
  previewImage: function(e) {
    var url = a.pdata(e).url,
      arr = a.pdata(e).arr;
    a.previewImage(url, arr, 'imgurl')
  },
  /**
   * 监听开始时间
   */
  listenerTime: function(e) {
    //调用setData()重新绘制
    this.setData({
      "bookData.book_time": e.detail.value,
    });
  },
  //跳转+收集表单id
  formSubmit1: function(k) {
    var e = {};
    e.formid = k.detail.formId;
    e.openid = getApp().getCache("userinfo").openid;
    e.username = getApp().getCache("userinfo").nickName;
    a.get('Market/getFormid', e, function(t) {
      console.log(t)
    })
    var auth_res = this.authCheck();
    if (!auth_res) {
      return;
    }
    a.jump('/yb_mingpian/pages/chats/chats');
  },
  to_chat: function() {
    a.jump('/yb_mingpian/pages/chats/chats');
  },
  getPhoneNumber: function(e) {
    t.getPhoneNumber(e, this, 1);
  },

  getMobile: function (e) {
    t.globalData.getphone = false;
    this.setData({
      getPhoneAuth: false
    })
    t.getPhoneNumber(e, this, 3);
  },

  to_path: function(e) {
    var i = a.pdata(e).i;
    if (i == 1) {
      a.jump('/yb_mingpian/pages/member/cart/index')
    } else if (i == 2) {
      a.jump('/yb_mingpian/pages/member/index/index')
    }
  },
  onShareAppMessage: function(e) {
    var that = this.data,
      uid = getApp().getCache('userinfo').uid ? getApp().getCache('userinfo').uid : 0;
    t.userlog(2, '商城', 'shop_relay');
    return {
      // title: that.name,
      path: '/yb_mingpian/pages/shop/index?pid=' + uid + "&card_id=" + t.globalData.card_id,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },

  /**
   * 跳转到web页面
   */
  toWeb: function(e) {
    var data = a.pdata(e);
    if (data.type == 'web_page') {
        var url = '/yb_mingpian/pages/web/index?url=' + escape(data.link) + '&name=' + data.name;
        a.jump(url);
    }
  },
  jiazai:function(){
    var o = this
  a.get("Card/getPhone",{
    user_id: t.getCache("userinfo").uid,
  }, function (res) {
    o.setData({
      company_status: res.company_status 
   })
  //  var that = this;
   if(o.data.company_status == 'ruzhu'){
    o.setData({
       store :"入驻"
     })
   }
   if(o.data.company_status == 'jindu'){
    o.setData({
       store :"进度"
     })
   }
   if(o.data.company_status == 'store'){
    o.setData({
       store :"小店"
     })
   }
 })
  },
// 跳转商城入驻页面
todatum: function(){
			wx.navigateTo({
			  url: '/yb_mingpian/pages/ruzhu/ruzhu',
			})
  },
 to_ruzhu:function() {
  var that = this;
  if(that.data.company_status == 'ruzhu'){
    wx.navigateTo({
      url: '/packageA/pages/ruzhu',
    })
  }
  if(that.data.company_status == 'jindu'){
    wx.navigateTo({
      url: '/yb_mingpian/pages/ruzhu/jieguo',
    })
  }
  if(that.data.company_status == 'store'){
    wx.navigateTo({
      url: '/yb_mingpian/pages/ruzhu/store',
    })
  }
  },
  //音频组件播放
  play_status_change: function (e) {
    var audioSrc = a.pdata(e).src;
    var audioIndex = a.pdata(e).index;
    var that = this;
    myAudio.src = audioSrc;

    if (that.data.audioIndex == audioIndex){
      if (that.data.isPlay) {
        myAudio.pause();
        that.setData({isPlay: false})
      } else {
        myAudio.play();
        that.setData({isPlay: true});
      }
    } else {
      if (that.data.audioIndex >= 0) {
        myAudio.pause();
        that.setData({
          currecttime: 0,
          nowtime: "00:00",
          audioIndex: audioIndex
        });
        myAudio.play();
      } else {
        that.setData({
          audioIndex: audioIndex,
          isPlay: true
        })
        myAudio.play();
      }
    }

    myAudio.onPlay(function (res) {
      console.log("onPlay !!!!!!!!!");
      that.setData({
        isPlay: true
      })
    })

    myAudio.onError(function (res) {
      console.log("onError !!!!!!!!!",res);
    })

    myAudio.onEnded(function (res) {
      console.log("onEnded !!!!!!!!!");
      that.setData({
        currecttime: 0,
        isPlay: false,
        nowtime: "00:00"
      });
      //myAudio.destroy()
    })
    myAudio.onPause(function (res) {
      console.log("onPause !!!!!!!!!");
      that.setData({
        isPlay: false,
      })
    })
    myAudio.onTimeUpdate(function (res) {
      console.log("onTimeUpdate !!!!!!!!!");
      console.log("currentTime",parseInt(myAudio.currentTime));
      console.log("duration",parseInt(myAudio.duration));
      if (!that.data.timechanging) {
        that.setData({
          currecttime: parseInt(myAudio.currentTime),
          nowtime: that.timeformat(parseInt(myAudio.currentTime)),
          duration: parseInt(myAudio.duration),
          totalTime: that.timeformat(parseInt(myAudio.duration)),
        })
      }
    })
  },

  // 视频播放
  video: function (event) {
    var index = event.currentTarget.dataset['index'];

    if (!this.data.videoIndex) { // 没有播放时播放视频
      this.setData({
        videoIndex: index
      })
      var videoContext = wx.createVideoContext('video' + index)
      videoContext.play()
    } else {
      //停止正在播放的视频
      var videoContextPrev = wx.createVideoContext('video' + this.data.videoIndex)
      videoContextPrev.stop()
      //将点击视频进行播放
      this.setData({
        videoIndex: index
      })
      var videoContextCurrent = wx.createVideoContext('video' + index)
      videoContextCurrent.play()
    }
  },

  timeformat: function (time) {
    var m = parseInt(time / 60);
    m = m < 10 ? "0" + m : "" + m;
    var s = time % 60;
    s = s < 10 ? "0" + s : "" + s;
    return m + ":" + s;
  },
  timechanging: function (res) {
    console.log("timechanging !!!!!!!!");
    this.setData({
      timechanging: true,
    })
  },
  timechange: function (res) {
    console.log("timechange !!!!!!!!");
    var time = res.detail.value;
    myAudio.seek(time);

    this.setData({
      currecttime: time,
      nowtime: this.timeformat(time),
      timechanging: false,
    })
    myAudio.play();
  },
  onUnload: function () {
    myAudio.destroy()
  },

})